package com.iemes.controller.workcenter_model;

import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.ItemBomFormMap;
import com.iemes.entity.ItemBomRelationFormMap;
import com.iemes.entity.ItemFormMap;
import com.iemes.entity.ItemSurrenalFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.service.workcenter_model.ItemService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;

@Controller
@RequestMapping("/workcenter_model/item/")
public class ItemController extends BaseController {
	
	@Inject
	private ItemService itemService;
	
	private Logger log = Logger.getLogger(this.getClass());
	
	private final String itemMaintenanceUrl = Common.BACKGROUND_PATH + "/workcenter_model/item/item_maintenance";

	@RequestMapping("item_maintenance")
	public String item_maintenance(Model model, HttpServletRequest request) {
		model.addAttribute("dataKeys", getUDefinedDataField("item_maintenance"));
		handlePageRes(model,request);
		return itemMaintenanceUrl;
	}
	
	@ResponseBody
	@RequestMapping("saveItem")
	@SystemLog(module="车间基础建模",methods="物料-保存物料")		//凡需要处理业务逻辑的.都需要记录操作日志
	public String saveItem(Model model,HttpServletRequest request){
		ItemFormMap itemFormMap = getFormMap(ItemFormMap.class);
		itemFormMap.put("create_time", DateUtils.getStringDateTime());
		itemFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		itemFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		try {
			itemService.saveItem(itemFormMap);
		}catch(BusinessException e) {
			log.error(e.getMessage());
			model.addAttribute(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 检索物料
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryItem")
	public String queryItem(Model model,HttpServletRequest request) {
		String itemNo = request.getParameter("item_no");
		String version = request.getParameter("version");
		try {
			//查物料
			ItemFormMap itemFormMap = new ItemFormMap();
			itemFormMap.put("item_no", itemNo);
			if (!StringUtils.isEmpty(version)) {
				itemFormMap.put("item_version", version);
			}
			itemFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			itemFormMap.put("orderby", " order by item_version");
			List<ItemFormMap> list = baseMapper.findByNames(itemFormMap);
			
			if (!ListUtils.isNotNull(list)) {
				log.error("未检索到物料编号编号为："+itemNo.toUpperCase()+"的信息");
				model.addAttribute("errorMessage","未检索到物料编号为："+itemNo.toUpperCase()+"的信息");
				handlePageRes(model,request);
				return itemMaintenanceUrl;
			}
			ItemFormMap itemFormMap2 = list.get(0);
			
			//查物料清单
			String bomId = itemFormMap2.getStr("bom_no");
			if (!StringUtils.isEmpty(bomId)) {
				List<ItemBomFormMap> itemBomFormMapList = baseMapper.findByAttribute("id", bomId, ItemBomFormMap.class);
				if (ListUtils.isNotNull(itemBomFormMapList)) {
					ItemBomFormMap itemBomFormMap = itemBomFormMapList.get(0);
					model.addAttribute("itemBom", itemBomFormMap);
				}
			}
			//查自定义数据
			getUDefinedDataValue(model,itemFormMap2.getStr("id"),"item_maintenance","dataKeys");
			model.addAttribute("itemFormMap", itemFormMap2);
			
			//查替代品信息
			List<ItemSurrenalFormMap> itemSurrenalList = baseMapper.findByAttribute("item_id", itemFormMap2.getStr("id"), ItemSurrenalFormMap.class);
			for (int i=0;i<itemSurrenalList.size();i++) {
				ItemSurrenalFormMap itemSurrenalFormMap = itemSurrenalList.get(i);
				
				List<ItemFormMap> list2 = baseMapper.findByAttribute("id", itemSurrenalFormMap.getStr("item_surrenal_id"), ItemFormMap.class);
				if (!ListUtils.isNotNull(list2)) {
					log.error("未查询到替代品的物料信息，请确定该信息是否错误或被删除！");
					model.addAttribute("errorMessage", "未查询到替代品的物料信息，请确定该信息是否错误或被删除！");
					handlePageRes(model,request);
					return itemMaintenanceUrl;
				}
				itemSurrenalFormMap.put("item_surrenal_no", list2.get(0).getStr("item_no"));
				
				List<ItemFormMap> list3 = baseMapper.findByAttribute("id", itemSurrenalFormMap.getStr("item_surrenal_usage"), ItemFormMap.class);
				if (!ListUtils.isNotNull(list3)) {
					log.error("未查询到有效装配的物料信息，请确定该信息是否错误或被删除！");
					model.addAttribute("errorMessage", "未查询到替代品的物料信息，请确定该信息是否错误或被删除！");
					handlePageRes(model,request);
					return itemMaintenanceUrl;
				}
				itemSurrenalFormMap.put("item_surrenal_usage_no", list3.get(0).getStr("item_no"));
			}
			model.addAttribute("itemSurrenal", itemSurrenalList);
		}catch(Exception e) {
			log.error(e.getMessage());
			model.addAttribute("errorMessage", e.getMessage());
			handlePageRes(model,request);
			return itemMaintenanceUrl;
		}
		model.addAttribute("successMessage", "检索成功");
		handlePageRes(model,request);
		return itemMaintenanceUrl;
	}
	
	/**
	 * 删除物料
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delItem")
	public String delItem(Model model,HttpServletRequest request) {
		String itemId = request.getParameter("item_id");
		try {
			if (StringUtils.isEmpty(itemId)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			
			//1.如果物料在物料清单中，不允许删除,需要先处理物料清单，把物料从物料清单里拿出来(可能有多个物料清单)
			ItemBomRelationFormMap itemBomRelationFormMap = new ItemBomRelationFormMap();
			itemBomRelationFormMap.put("item_id", itemId);
			List<ItemBomRelationFormMap> listItemBomRelationFormMap = baseMapper.findByNames(itemBomRelationFormMap);
			if(ListUtils.isNotNull(listItemBomRelationFormMap)){
				String bindItemBomNo = "";
				for(int i=0;i<listItemBomRelationFormMap.size();i++) {
					ItemBomRelationFormMap map = listItemBomRelationFormMap.get(i);
				    List<ItemBomFormMap> listItemBomFormMap = baseMapper.findByAttribute("id", map.getStr("item_bom_id"), ItemBomFormMap.class);
				    if(!ListUtils.isNotNull(listItemBomFormMap)) {
				    	throw new BusinessException("无法此物料所在的物料清单Id " + map.getStr("item_bom_id") + " 的详细信息，请联系系统管理员！");
				    }
				    ItemBomFormMap itemBomFormMap = listItemBomFormMap.get(0);
					if(StringUtils.isEmpty(bindItemBomNo)) {
						bindItemBomNo = itemBomFormMap.getStr("item_bom_no");
					}else {
						bindItemBomNo += "," + itemBomFormMap.getStr("item_bom_no");
					}
				}
				throw new BusinessException("物料删除失败！"+ "此物料在物料清单 " + bindItemBomNo + " 中，无法执行删除！");
			}
			
			//2.如果物料在替代物料中，不允许删除
			ItemSurrenalFormMap itemSurrenalFormMap = new ItemSurrenalFormMap();
			itemSurrenalFormMap.put("item_surrenal_id", itemId);
			List<ItemSurrenalFormMap> listItemSurrenalFormMap = baseMapper.findByNames(itemSurrenalFormMap);
			if(ListUtils.isNotNull(listItemSurrenalFormMap)){
				String bindSurrenaledItemNo = "";
				for(int i=0;i<listItemSurrenalFormMap.size();i++) {
					ItemSurrenalFormMap map = listItemSurrenalFormMap.get(i);
				    List<ItemFormMap> listItemFormMap = baseMapper.findByAttribute("id", map.getStr("item_id"), ItemFormMap.class);
				    if(!ListUtils.isNotNull(listItemFormMap)) {
				    	throw new BusinessException("无法找到此物料所替换物料Id " + map.getStr("item_bom_id") + " 的详细信息，请联系系统管理员！");
				    }
				    ItemFormMap itemFormMap = listItemFormMap.get(0);
					if(StringUtils.isEmpty(bindSurrenaledItemNo)) {
						bindSurrenaledItemNo = itemFormMap.getStr("item_no");
					}else {
						bindSurrenaledItemNo += "," + itemFormMap.getStr("item_no");
					}
				}
				throw new BusinessException("物料删除失败！"+ "此物料在物料 " + bindSurrenaledItemNo + " 的替代列表中，无法执行删除！");
			}
			
			//3.如果物料在工单中，不允许删除
			ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
			shoporderFormMap.put("shoporder_item_id", itemId);
			List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(shoporderFormMap);
			if (ListUtils.isNotNull(listShoporderFormMap)) {
				String bindShoporderNo = "";
				for(int i=0;i<listShoporderFormMap.size();i++) {
					ShoporderFormMap map = listShoporderFormMap.get(i);
					if(StringUtils.isEmpty(bindShoporderNo)) {
						bindShoporderNo = map.getStr("shoporder_no");
					}else {
						bindShoporderNo += "," + map.getStr("shoporder_no");
					}
				}
				throw new BusinessException("物料删除失败！"+ "此物料已绑定了工单 " + bindShoporderNo + "，无法执行删除！");				
			}
			
			//4.执行删除
			itemService.delItem(itemId);
		}catch(BusinessException e) {
			log.error(e.getMessage(), e);
			model.addAttribute("errorMessage", e.getMessage());
			handlePageRes(model,request);
			return itemMaintenanceUrl;
		}
		model.addAttribute("successMessage", "删除成功");
		handlePageRes(model,request);
		return itemMaintenanceUrl;
	}
}
